const express = require('express');
const mongoose = require('mongoose');
const consul = require('consul');

const app = express();
const PORT = 3000;

// 中间件
app.use(express.json());

// Consul 配置
const consulClient = consul({
  host: process.env.CONSUL_HOST || 'consul-client',
  port: process.env.CONSUL_PORT || 8500
});

// MongoDB 连接
mongoose.connect(process.env.MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

// 简单的用户模型
const UserSchema = new mongoose.Schema({
  name: String,
  email: String
});
const User = mongoose.model('User', UserSchema);

// 健康检查端点
app.get('/health', (req, res) => {
  res.json({ 
    status: 'OK', 
    service: 'express-app',
    timestamp: new Date().toISOString(),
    instance: process.env.HOSTNAME || 'local'
  });
});

// API 路由
app.get('/api/info', (req, res) => {
  res.json({
    message: 'Hello from Express with Consul!',
    servedBy: process.env.HOSTNAME || 'unknown',
    time: new Date().toISOString()
  });
});

app.post('/api/users', async (req, res) => {
  try {
    const user = new User(req.body);
    await user.save();
    res.json(user);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.get('/api/users', async (req, res) => {
  try {
    const users = await User.find();
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 注册服务到 Consul
async function registerService() {
  const serviceId = `express-app-${process.env.HOSTNAME || 'local'}`;
  
  await consulClient.agent.service.register({
    name: 'express-app',
    id: serviceId,
    address: serviceId,
    port: PORT,
    check: {
      http: `http://${serviceId}:${PORT}/health`,
      interval: '10s'
    }
  });
  
  console.log(`✅ Service registered: ${serviceId}`);
}

// 启动服务器
app.listen(PORT, '0.0.0.0', async () => {
  console.log(`🚀 Express server running on port ${PORT}`);
  
  try {
    await registerService();
  } catch (error) {
    console.log('❌ Consul registration failed:', error.message);
  }
});
